# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponseRedirect
from django.template.context import RequestContext
from django.contrib import messages

from mdcssport.mdcsapp.models import News
from mdcssport.mdcsapp.forms import NewsForm

def news(request):
    news_list = News.objects.order_by('-date_updated')
    news_paginator = Paginator(news_list, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        news = news_paginator.page(page)
    except (EmptyPage, InvalidPage):
        news = news_paginator.page(news_paginator.num_pages)

    return render_to_response('news/news.html', {"news": news},
        context_instance=RequestContext(request))

def one_news(request, news_id):
    one_news = get_object_or_404(News, pk=int(news_id))
    return render_to_response('news/one_news.html', {"one_news": one_news},
        context_instance=RequestContext(request))

def news_edit(request, news_id = 0):
    news = None
    if news_id != 0:
        news = get_object_or_404(News, pk=int(news_id))

    # proveravamo privilegije rucno
    if news == None and not request.user.has_perm('mdcsapp.add_news'):
        return HttpResponseRedirect('/mdcs/')
    if news != None:
        if not request.user.is_superuser:
            if not (request.user.has_perm('mdcsapp.change_news') and request.user.get_profile() == news.user):
                return HttpResponseRedirect('/mdcs/')

    if request.method == 'POST':
        news_form = NewsForm(request.POST, instance = news)
        if news_form.is_valid():
            if news == None:
                inserted_news = news_form.save(commit = False)
                inserted_news.user = request.user.get_profile()
                inserted_news.save()
                messages.add_message(request, messages.INFO, "Vest uspešno uneta")
            else:
                news_form.save()
                messages.add_message(request, messages.INFO, "Vest uspešno izmenjena")
            return HttpResponseRedirect('/mdcs/')
    else:
        if news == None:
            news_form = NewsForm()
        else:
            news_form = NewsForm(instance = news)

    return render_to_response('news/news_edit.html', {'news_id': news_id, 'news_form': news_form},
        context_instance=RequestContext(request))